package menus;

import game.TileMap;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import controller.Controller;

@SuppressWarnings("serial")
public class MapSelection extends JFrame {

	private JList<File> list = null;
	private Controller controller = null;
	private String connType = null;
	private final MapViewer mapViewer;
	
	/**
	 * Create the frame.
	 */
	public MapSelection(Controller cont) {
		setResizable(false);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.controller = cont;
		this.connType = controller.conn.toString();
		
		if(connType.equals("Server"))
			setTitle("Map Selection: Host");
		else 
			setTitle("Map Selection: Client");
	
		File[] fileList = new File("maps").listFiles();
		mapViewer = new MapViewer(fileList);
		
		addComponentsToPane(this.getContentPane(), fileList);
		this.pack();
	}
	
	public void addComponentsToPane(final Container pane, File[] fileList) {
		list = new JList<File>();
		list.setListData(fileList);
		list.setSelectedIndex(0);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		ListSelectionModel listSelectionModel = list.getSelectionModel();
		
		if (connType.equals("Server")) {
			listSelectionModel.addListSelectionListener(mapViewer);
		} // The client does not register the listener
		
		mapViewer.setPreferredSize(new Dimension(320, 320));
		
		JButton selectButton = new JButton("Select");
		
		pane.add(mapViewer, BorderLayout.WEST);
		pane.add(list, BorderLayout.EAST);
		
		if(connType.equals("Server")){
			pane.add(selectButton, BorderLayout.SOUTH);
			 selectButton.addActionListener(new ActionListener() {
				 
		            public void actionPerformed(ActionEvent e)
		            {
		                //Execute when button is pressed
		            	// TODO select map
		            	// controller.conn.send("MAP:"+fileList[list.getSelectedIndex()].toString())
		            }
		        });      
		}
	}

	private void resizeFrame() {
		this.pack();
	}

	
	private class MapViewer extends JPanel implements ListSelectionListener {
		File[] fileList;
		TileMap selectedMap;

		@Override
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.clearRect(0, 0, getWidth(), getHeight());
			// TODO need to resize according to the map
			for (int i = 0; i < selectedMap.getHeight(); i++) {
				for (int j = 0; j < selectedMap.getWidth(); j++) {
					int x = i * 32;
					int y = j * 32;
					Image terrainImage = controller.assets.getTerrain(selectedMap.getTerrain()[j][i]);
					g.drawImage(terrainImage, x, y, this);
				}
			}
		}

		public MapViewer(File[] fileList) {
			this.fileList = fileList;
			try {
				this.selectedMap = new TileMap(fileList[0].toString());
			} catch (ClassNotFoundException | IOException e) {
				e.printStackTrace();
				System.exit(0);
			}
		}
		
		/**
		 * Only the Server/Host have the listener registered.
		 */
		@Override
		public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting() == false) {
				String mapName = fileList[list.getSelectedIndex()].toString();
				selectAndRepaintMap(mapName);
				controller.conn.send(mapName);
				System.out.println(mapName+" sent");
			}
		}
		
		private void selectAndRepaintMap(String mapName){
			try {
				selectedMap = new TileMap(mapName);
			} catch (ClassNotFoundException | IOException e) {
				e.printStackTrace();
			}

			int newXsize;
			int newYsize;
			if(selectedMap.getWidth() > 5)
				newXsize = selectedMap.getWidth()*32;
			else
				newXsize = 5*32;
			if(selectedMap.getHeight() > 5)
				newYsize = selectedMap.getHeight()*32;
			else
				newYsize = 5*32;

			Dimension newDims = new Dimension(newXsize, newYsize);
			this.setPreferredSize(newDims);
			
			resizeFrame();
			this.repaint();
		}
	}
	
	public void repaintMap(String mapName){
		mapViewer.selectAndRepaintMap(mapName);
	}
}